package com.haoxi.gateway.test.gatewayserver;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.TestConfConst;
import com.haoxi.gateway.test.util.Cfg;

/**
 * @author Administrator Window - Preferences - Java - Code Style - Code
 *         Templates
 */

public abstract class PooledServer {
    protected static final Log log = LogFactory.getLog(PooledServer.class);
    protected int maxConnections;
    protected int listenPort;
    protected ServerSocket serverSocket;
    private boolean start_stop = false;

    public PooledServer(int aListenPort, int maxConnections) {
        initTestConf();
        listenPort = TestConfConst.localPort;
        this.maxConnections = maxConnections;
        this.start_stop = true;
        
        // init processer
        setUpHandlers();
    }

    public void initTestConf() {
        try {
            Cfg cfg = new Cfg("src/testconf/gatewayconf.xml");
            TestConfConst.delivertimes = cfg.getInt("delivertimes", 20);
            TestConfConst.deliverstate = cfg.getInt("deliverstate", 0);
            TestConfConst.dest_Id = cfg.get("Dest_Id", "");
            TestConfConst.service_Id = cfg.get("Service_Id", "");
            TestConfConst.msgFmt = cfg.getInt("Msg_Fmt", 15);
            TestConfConst.src_terminal_Id = cfg.get("Src_terminal_Id", "");
            TestConfConst.src_terminal_type = cfg
                    .getInt("Src_terminal_type", 0);
            TestConfConst.msg_Content = cfg.get("Msg_Content", "");
            TestConfConst.linkID = cfg.get("LinkID", "");
            TestConfConst.deliverstate = cfg.getInt("deliverstate", 0);
            TestConfConst.protocoltype = cfg.get("protocoltype", "cmpp");
            TestConfConst.icpid = cfg.getInt("icpid", 1234);
            TestConfConst.sphost = cfg.get("sphost", "127.0.0.1");
            TestConfConst.spport = cfg.getInt("spport", 127);
            TestConfConst.login_Name = cfg.get("loginName", "");
            TestConfConst.login_Passowrd = cfg.get("loginPassword", "");
            TestConfConst.localPort=cfg.getInt("localPort", 5100);
            TestConfConst.spLogin_Name=cfg.get("spLoginName", "");
            TestConfConst.spLogin_Password=cfg.get("spLoginPassword", null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 判断start_stop，提供服务
     */
    public void startServer() {
        try {
            ServerSocket server = new ServerSocket(listenPort, 5);
            log.info("server is start!listenPort" + listenPort);
            Socket incomingConnection = null;
            if (TestConfConst.SGIP.equals(TestConfConst.protocoltype))
            {
                ReceiverSpThread spThread = new ReceiverSpThread();
                spThread.start();
            }
            while (start_stop) {
                incomingConnection = server.accept();
                log.debug("client connect success:"+incomingConnection.getInetAddress().toString());
                // 启动定时线程，向客户端发deliver消息
//                if (TestConfConst.CMPP.equals(TestConfConst.protocoltype)) {
//                    Timer timer = new Timer(true);
//                    timer.schedule(new SendDeliverTask(incomingConnection),
//                            new Date(), sendDeliverTime);
//                }
                handleConnection(incomingConnection);
            }
        } catch (BindException e) {
            log.error("Unable to bind to port:" + listenPort, e);
        } catch (IOException e) {
            log.error("Unable to instantiate a ServerSocket on port:"
                    + listenPort, e);
        }
    }

    /**
     * 处理请求
     * 
     * @param connectionToHandle socket请求
     */
    abstract public void handleConnection(Socket connectionToHandle);

    /**
     * init process runner
     * 
     */
    private void setUpHandlers() {
        for (int i = 0; i < maxConnections; i++) {
            PooledConnHandler currentHandler = new MOConnHandler();
            new Thread(currentHandler, "Handler_" + i).start();
        }
    }

    /**
     * @return Returns the start_stop.
     */
    public boolean isStart_stop() {
        return this.start_stop;
    }

    /**
     * @param start_stop The start_stop to set.
     */
    public void stopServer() {
        this.start_stop = false;
    }
    public static void main(String[] args)
    {
        try
        {
        Cfg cfg = new Cfg("src/testconf/gatewayconf.xml");
        System.out.println(cfg.getInt("delivertimes", 20));
        System.out.println(cfg.get("Dest_Id", ""));
        TestConfConst.service_Id = cfg.get("Service_Id", "");
        TestConfConst.msgFmt = cfg.getInt("Msg_Fmt", 15);
        TestConfConst.src_terminal_Id = cfg.get("Src_terminal_Id", "");
        TestConfConst.src_terminal_type = cfg
                .getInt("Src_terminal_type", 0);
        TestConfConst.msg_Content = cfg.get("Msg_Content", "");
        TestConfConst.linkID = cfg.get("LinkID", "");
        TestConfConst.deliverstate = cfg.getInt("deliverstate", 0);
        TestConfConst.protocoltype = cfg.get("protocoltype", "cmpp");
        TestConfConst.icpid = cfg.getInt("icpid", 1234);
        TestConfConst.sphost = cfg.get("sphost", "127.0.0.1");
        TestConfConst.spport = cfg.getInt("spport", 127);
        TestConfConst.login_Name = cfg.get("loginName", "");
        TestConfConst.login_Passowrd = cfg.get("loginPassword", "");
        
        }
        catch(IOException ex)
        {
            
        }
    }

}